//
//  String+DBExtension.swift
//  DBCA
//
//  Created by mugua on 2024/6/30.
//

import Foundation

extension String {
    
    public var db_isValidString: Bool {
        let trimmedStr = self.trimmingCharacters(in: .whitespacesAndNewlines)
        return trimmedStr.isEmpty
    }
    
    public var db_safeString: String {
        if self.db_isValidString {
            return self
        }
        return ""
    }
    
    public var db_getURLParameters: [String: Any] {
        
        var params: [String: Any] = [:]
        
        guard let index = self.firstIndex(of: "?") else {
            return [:]
        }
        
        let startIndex = self.index(index, offsetBy: 1)
        
        let parametersString = self[startIndex..<self.endIndex]
        
        if parametersString.contains("&") {
            let urlComponents = parametersString.components(separatedBy: "&")
            for keyValue in urlComponents {
                let pairComponents = keyValue.components(separatedBy: "=")
                
                if pairComponents.count == 1 {
                    return [:]
                }
                
                var key, value: String?
                
                if pairComponents.count == 2 {
                    key = pairComponents.first!.removingPercentEncoding
                    value = pairComponents.last!.removingPercentEncoding
                } else if pairComponents.count > 2 {
                    key = pairComponents.first!.removingPercentEncoding
                    let valueCompoent = keyValue.components(separatedBy: String("\(pairComponents.first!)=")).last
                    value = valueCompoent?.removingPercentEncoding
                }
                
                guard let key = key, let value = value else { return [:] }
                
                params[key] = value
            }
            
        } else {
            
            let pairComponents = parametersString.components(separatedBy: "=")
            
            if pairComponents.count == 1 {
                return [:]
            }
            
            var key, value: String?
            
            if pairComponents.count == 2 {
                key = pairComponents.first!.removingPercentEncoding
                value = pairComponents.last!.removingPercentEncoding
            } else if pairComponents.count > 2 {
                key = pairComponents.first!.removingPercentEncoding
                let valueCompoent = parametersString.components(separatedBy: String("\(pairComponents.first!)=")).last
                value = valueCompoent?.removingPercentEncoding
            }
            
            guard let key = key, let value = value else { return [:] }
            
            params[key] = value
        }
        
        return params
    }
}
